home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / glchess / config.py < prev    next >
Text File  |  2009-09-22  |  7KB  |  228 lines

  1. # -*- coding: utf-8 -*-
  2. from defaults import *
  3.  
  4. try:
  5.     import gconf
  6.     import gobject
  7. except ImportError:
  8.     haveGConfSupport = False
  9.     _notifiers = {}
  10.     _values = {}
  11.  
  12.     import xml.dom.minidom
  13.     document = None
  14.     try:
  15.         document = xml.dom.minidom.parse(CONFIG_FILE)
  16.     except IOError:
  17.         pass
  18.     except xml.parsers.expat.ExpatError:
  19.         print 'Configuration at ' + CONFIG_FILE + ' is invalid, ignoring'
  20.     else:
  21.         print 'Loading configuration from ' + CONFIG_FILE
  22.  
  23.     def _bool(string):
  24.         return string == 'True'
  25.         
  26.     valueTypes = {'int': int, 'bool': _bool, 'float': float, 'str': str}
  27.     
  28.     if document is not None:
  29.         elements = document.getElementsByTagName('config')
  30.         
  31.         for e in elements:
  32.             for n in e.getElementsByTagName('value'):
  33.                 try:
  34.                     name = n.attributes['name'].nodeValue
  35.                 except KeyError:
  36.                     continue
  37.                 try:
  38.                     valueType = n.attributes['type'].nodeValue
  39.                 except KeyError:
  40.                     continue
  41.                 if len(n.childNodes) != 1 or n.childNodes[0].nodeType != n.TEXT_NODE:
  42.                     continue
  43.                 valueString = n.childNodes[0].nodeValue
  44.                 
  45.                 try:
  46.                     value = valueTypes[valueType](valueString)
  47.                 except KeyError:
  48.                     continue
  49.  
  50.                 _values[name] = value
  51.  
  52. else:
  53.     haveGConfSupport = True
  54.     _GCONF_DIR = '/apps/glchess/'
  55.     _config = gconf.client_get_default()
  56.     try:
  57.         _config.add_dir(_GCONF_DIR[:-1], gconf.CLIENT_PRELOAD_NONE)
  58.     except gobject.GError:
  59.         pass
  60.     
  61.     _gconfGetFunction = {gconf.VALUE_BOOL: gconf.Value.get_bool,
  62.                          gconf.VALUE_FLOAT: gconf.Value.get_float,
  63.                          gconf.VALUE_INT: gconf.Value.get_int,
  64.                          gconf.VALUE_STRING: gconf.Value.get_string}
  65.                          
  66.     _gconfSetFunction = {bool:    _config.set_bool,
  67.                          float:   _config.set_float,
  68.                          int:     _config.set_int,
  69.                          str:     _config.set_string,
  70.                          unicode: _config.set_string}
  71.               
  72. # Config default values
  73. _defaults = {'show_toolbar':                     True,
  74.              'show_history':                     True,
  75.              'maximised':                        False,
  76.              'fullscreen':                       False,
  77.              'show_3d':                          False,
  78.              'show_3d_smooth':                   False,             
  79.              'show_move_hints':                  True,
  80.              'move_format':                      'human',
  81.              'promotion_type':                   'queen',
  82.              'board_view':                       'human',
  83.              'show_comments':                    False,
  84.              'show_numbering':                   False,
  85.              'enable_networking':                True,
  86.              'load_directory':                   '',
  87.              'save_directory':                   '',
  88.              'new_game_dialog/move_time':        0,
  89.              'new_game_dialog/white/type':       '',
  90.              'new_game_dialog/white/difficulty': '',
  91.              'new_game_dialog/black/type':       '',
  92.              'new_game_dialog/black/difficulty': ''}
  93.  
  94. class Error(Exception):
  95.     """Exception for configuration use"""
  96.     pass
  97.  
  98. def get(name):
  99.     """Get a configuration value.
  100.     
  101.     'name' is the name of the value to get (string).
  102.     
  103.     Raises an Error exception if the value does not exist.
  104.     """
  105.     if haveGConfSupport:
  106.         try:
  107.             entry = _config.get(_GCONF_DIR + name)
  108.         except gobject.GError:
  109.             entry = None
  110.         
  111.         if entry is None:
  112.             try:
  113.                 return _defaults[name]
  114.             except KeyError:
  115.                 raise Error('No config value: ' + repr(name))
  116.  
  117.         try:
  118.             function = _gconfGetFunction[entry.type]
  119.         except KeyError:
  120.             raise Error('Unknown value type')
  121.         
  122.         return function(entry)
  123.         
  124.     else:
  125.         try:
  126.             return _values[name]
  127.         except KeyError:
  128.             try:
  129.                 return _defaults[name]
  130.             except KeyError:
  131.                 raise Error('No config value: ' + repr(name))
  132.  
  133. def set(name, value):
  134.     """Set a configuration value.
  135.     
  136.     'name' is the name of the value to set (string).
  137.     'value' is the value to set to (int, str, float, bool).
  138.     """
  139.     if haveGConfSupport:
  140.         try:
  141.             function = _gconfSetFunction[type(value)]
  142.         except KeyError:
  143.             raise TypeError('Only config values of type: int, str, float, bool supported')
  144.         else:
  145.             try:
  146.                 function(_GCONF_DIR + name, value)
  147.             except gobject.GError:
  148.                 pass
  149.  
  150.     else:
  151.         # Debounce
  152.         try:
  153.             oldValue = _values[name]
  154.         except KeyError:
  155.             pass
  156.         else:
  157.             if oldValue == value:
  158.                 return
  159.         
  160.         # Use new value and notify watchers
  161.         _values[name] = value
  162.         try:
  163.             watchers = _notifiers[name]
  164.         except KeyError:
  165.             pass
  166.         else:
  167.             for func in watchers:
  168.                 func(name, value)
  169.                 
  170.         # Save configuration
  171.         _save()
  172.         
  173. def default(name):
  174.     set(name, _defaults[name])
  175.                 
  176. def _watch(client, _, entry, (function, name)):
  177.     value = get(name)
  178.     function(name, value)
  179.  
  180. def watch(name, function):
  181.     """
  182.     """
  183.     if haveGConfSupport:
  184.         try:
  185.             _config.notify_add(_GCONF_DIR + name, _watch, (function, name))
  186.         except gobject.GError:
  187.             pass
  188.     else:
  189.         try:
  190.             watchers = _notifiers[name]
  191.         except KeyError:
  192.             watchers = _notifiers[name] = []            
  193.         watchers.append(function)
  194.  
  195. def _save():
  196.     """Save the current configuration"""
  197.     if haveGConfSupport:
  198.         return
  199.     
  200.     document = xml.dom.minidom.Document()
  201.     
  202.     e = document.createComment('Automatically generated by glChess, do not edit!')
  203.     document.appendChild(e)
  204.     
  205.     root = document.createElement('config')
  206.     document.appendChild(root)
  207.     
  208.     valueNames = {int: 'int', bool: 'bool', float: 'float', str: 'str', unicode: 'str'}
  209.  
  210.     names = _values.keys()
  211.     names.sort()
  212.     for name in names:
  213.         value = _values[name]
  214.         e = document.createElement('value')
  215.         root.appendChild(e)
  216.         e.setAttribute('name', name)
  217.         e.setAttribute('type', valueNames[type(value)])
  218.         valueElement = document.createTextNode(str(value))
  219.         e.appendChild(valueElement)
  220.  
  221.     try:
  222.         f = file(CONFIG_FILE, 'w')
  223.     except IOError:
  224.         pass
  225.     else:
  226.         document.writexml(f)
  227.         f.close()
  228.